import { ModalC, FormGroup, DATA_ENTRY, SecondHeaderC, ProductListC, PrimaryGhostC, AdvancedSearch, TableC } from '@/src/comps';
import { UploadC } from '@/src/components';
import React, { useEffect, useRef, useState, useMemo } from 'react';
import PropTypes from 'prop-types';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import styles from './modalModule.less';
import { message, Space, Popover, notification, Tag } from 'antd';
import { connect } from 'dva';
import { getColumnIntoWidth } from '@/src/utils/utils';
import { parseExcelFile, compareArrays } from '@/src/utils/commonFunc';
import moment from 'moment/moment';
import { cloneDeep } from 'lodash';
import { exportFile } from 'table-xlsx';

let timerId;
const SingleTenantReportModal = (props) => {
  const [initDate, setInitDate] = useState(
    moment()
      .quarter(moment().quarter() - 1)
      .endOf('quarter'),
  ); // 上个季度最后一天
  const {
    visible,
    operate,
    productManageM,
    loading,
    dispatch,
    globalM: { dataDictionary = {} },
    tenantManageM: { sceneList, templateList },
  } = props;
  const [dataCompareOpen, setDataCompareOpen] = useState(false); // 数据对比气泡
  const [dataSource, setDataSource] = useState([]); // 列表data
  const [defaultSelect, setDefaultSelect] = useState();
  const [flag, setFlag] = useState(true); // 点击重置不查询
  const [resetFields, setResetFields] = useState(false); // 重置产品
  const [productNum, setProductNum] = useState(0); // 产品数量
  const [currentTenant, setCurrentTenant] = useState(null);
  const [managerName, setManagerName] = useState(undefined); // 租户名称
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 产品code[]
  const [sortedInfo, setSortedInfo] = useState({}); // 排序
  const [searchParams, setSearchParams] = useState({}); // table查询参数
  const [pageInfo, setPageInfo] = useState({
    numInPage: 20,
    currentPage: 1,
    total: 0,
  });
  const formRef = useRef(); // 表单ref
  const productListRef = useRef(); // 产品下拉ref
  const { dictMapSelect } = productManageM;
  const columnsMemo = useMemo(() => {
    return [
      { dataIndex: 'productName', title: '产品名称', key: 'productName' },
      { dataIndex: 'gzCode', title: '估值代码', key: 'gzCode', sorter: true, width: 150, align: 'right' },
      {
        dataIndex: 'productStatus',
        title: '产品状态',
        key: 'productStatus',
        width: 100,
        sorter: true,
        align: 'right',
        render: (text, record) => {
          const arrs = dictMapSelect.BAXX_CPZT && dictMapSelect.BAXX_CPZT.filter((item) => item.value == text);
          return (arrs?.length && arrs[0].title) || (text ? text : '--');
        },
      },
      { dataIndex: 'startDate', title: '成立日', key: 'startDate', sorter: true, width: 100, align: 'right', render: (text) => (text ? moment(text).format('YYYY-MM-DD') : '--') },
      { dataIndex: 'endDate', title: '到期日', key: 'endDate', sorter: true, width: 100, align: 'right', render: (text) => (text ? moment(text).format('YYYY-MM-DD') : '--') },
    ];
  }, [sortedInfo, dictMapSelect]);
  const changeTenant = (tenant) => {
    setCurrentTenant(tenant?.key);
    setManagerName(tenant?.info?.title);
    props.form.resetFields(['productdataIndex']);
    setDataSource([]);
    setPageInfo({
      ...pageInfo,
      total: 0,
    });
  };
  // 获取table 产品数据
  const getTableDate = () => {
    dispatch({
      type: 'productManageM/getList',
      payload: {
        currentPage: pageInfo.currentPage ?? 1,
        numInPage: 9999,
        ...searchParams,
        order: sortedInfo.order,
        columnKey: sortedInfo.order ? (sortedInfo.columnKey === 'gzCode' ? 'code' : sortedInfo.columnKey) : undefined,
        tenant: currentTenant ?? undefined,
      },
      callback: (res) => {
        if (res) {
          setDataSource(res.dataSource);
          setPageInfo({
            ...pageInfo,
            total: res.pageInfo.total,
          });
          setFlag(true);
        }
      },
    });
  };

  useEffect(() => {
    if (currentTenant) {
      if (flag === true) getTableDate();
    }
  }, [pageInfo.currentPage, pageInfo.numInPage, searchParams, sortedInfo]);

  const onGetProductListData = (data) => setProductNum(data.length); // 获取产品数量
  useEffect(() => {
    dispatch({
      type: 'productManageM/fetchDictByKeys', // 字典下拉
      payload: {
        dictData: dataDictionary,
      },
    });
    dispatch({
      type: 'tenantManageM/getScenes', // 情景 模板 下拉
      payload: {},
    });
    dispatch({
      type: 'tenantManageM/getTemplate',
      payload: {},
    });
    return () => {
      clearInterval(timerId);
      timerId = null;
    };
  }, []);

  // 查询
  const handleSearch = (e) => {
    if (!currentTenant) return message.warning('请选择租户');
    props.form.resetFields(['productdataIndex']);
    if (e === undefined) {
      setSearchParams({});
      setSortedInfo({});
      setFlag(false);
      setDefaultSelect(undefined);
      return;
    }
    setFlag(true);
    setSearchParams({
      ...searchParams,
      productStatus: e.productStatus ? e.productStatus.join(',') : undefined,
      startDateEnd: e.startDateEnd ? moment(e.startDateEnd).format('YYYY-MM-DD') : undefined,
      startDateStart: e.startDateStart ? moment(e.startDateStart).format('YYYY-MM-DD') : undefined,
      endDateEnd: e.endDateEnd ? moment(e.endDateEnd).format('YYYY-MM-DD') : undefined,
      endDateStart: e.endDateStart ? moment(e.endDateStart).format('YYYY-MM-DD') : undefined,
    });
  };
  // 选择产品
  const handleSelectProduct = (productInfo) => {
    if (!productInfo) return;
    const currentportfolioCode = productInfo.info.portfolioCode;
    const isExist = dataSource.some((v) => v.gzCode === currentportfolioCode);
    const isExistIndex = dataSource.findIndex((v) => v.gzCode === currentportfolioCode);
    const v = document.querySelector('#currentScrollTable .ant-table-body');
    const rowHeight = document.querySelector('#currentScrollTable .ant-table-row')?.clientHeight;
    // 存在相同的产品
    if (isExist) {
      const data = cloneDeep(dataSource);
      const splicedItem = data[isExistIndex]; // 滚动到指定位置
      v.scrollTop = rowHeight * isExistIndex;
      console.log(isExistIndex);
      setDefaultSelect(splicedItem.gzCode);
      setResetFields(!resetFields);
      return message.warning('该产品已在列表，请勿重复添加。');
    } else {
      const data = cloneDeep(dataSource);
      data.unshift({
        gzCode: currentportfolioCode,
        productName: productInfo.info.portfolioName,
        productStatus: productInfo.info.status,
        startDate: productInfo.info.selectStartDate,
        endDate: productInfo.info.selectEndDate,
        productType: productInfo.info.type,
      });
      setDefaultSelect(currentportfolioCode);
      setDataSource(data);
      v.scrollTop = 0;
    }
  };
  const resetProduct = () => {
    props.form.resetFields(['productdataIndex']);
  };
  useEffect(() => resetProduct(), [resetFields]);
  const changeTable = (pagination, filters, sorter) => {
    setPageInfo({
      ...pageInfo,
      numInPage: pagination.pageSize,
      currentPage: pagination.current,
    });
    setSortedInfo(sorter);
  };
  // 删除
  const batchDel = () => {
    const data = cloneDeep(dataSource);
    const res = data.filter((item) => !selectedRowKeys.includes(item.gzCode));
    setResetFields(!resetFields);
    setSelectedRowKeys([]);
    setDataSource(res);
  };
  const exportCurrentProduct = () => {
    exportFile({
      fileName: '单租户报告申请的当前产品.xlsx',
      dataSource,
      columns: columnsMemo,
      headerCellStyle: { fillFgColorRgb: 'e8efff' }, // header行的填充颜色
    });
  };
  const handleDataComparison = (file) => {
    const keyMapSheet1 = { 名称: 'productName', 代码: 'gzCode', 成立日: 'startDate', 管理人: 'managerName' };
    if (file) {
      parseExcelFile(file, [keyMapSheet1]).then((res) => {
        const sheetData = res[0].dataSource; // 表数据
        if (sheetData.length === 0 || sheetData[0].gzCode === undefined || sheetData[0].managerName === undefined) {
          return message.warning('导入的文件内未匹配到代码列或管理人列');
        }
        const sameManageNameData = sheetData.filter((ele) => ele.managerName === managerName); // 找到表格中“管理人”列同名单数据
        if (sameManageNameData.length === 0) {
          message.info(`在导入的文件中，未找到${managerName}管理人，请确认导入数据的正确性。`);
        } else {
          // unmatchedDataArr2:列表中包含但文件中不包含的产品, unmatchedDataArr1文件中包含但列表中不包含的产品
          const { unmatchedDataArr1, unmatchedDataArr2 } = compareArrays(sameManageNameData, dataSource, 'gzCode');
          if (unmatchedDataArr1.length === 0 && unmatchedDataArr2.length === 0) {
            message.success(`导入文件中 ${managerName} 管理人的产品与产品列表完全一致。`);
          } else {
            notification.info({
              className: styles.notificationModal,
              message: '数据对比结果',
              placement: 'top',
              description: (
                <div className={styles.notificationModalHeight}>
                  {unmatchedDataArr1.length > 0 && (
                    <div style={{ marginBottom: 16 }}>
                      <div style={{ marginLeft: -14 }}>
                        <SecondHeaderC title='文件中包含但列表中不包含的产品' />
                      </div>
                      {unmatchedDataArr1.map((v) => (
                        <Tag style={{ marginBottom: 5 }} color='geekblue'>
                          {v?.gzCode}
                        </Tag>
                      ))}
                    </div>
                  )}
                  {unmatchedDataArr2.length > 0 && (
                    <div style={{ marginBottom: 16 }}>
                      <div style={{ marginLeft: -14 }}>
                        <SecondHeaderC title='列表中包含但文件中不包含的产品' />
                      </div>
                      {unmatchedDataArr2.map((v) => (
                        <Tag style={{ marginBottom: 5 }} color='geekblue'>
                          {v.gzCode}
                        </Tag>
                      ))}
                    </div>
                  )}
                </div>
              ),
            });
          }
        }
      });
      setDataCompareOpen(false);
    } else {
      message.warning('请先先选择对比文件');
    }
  };
  const widthColumns = getColumnIntoWidth(columnsMemo, dataSource);
  const formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 14 } };
  return (
    <div className={styles.SingleTenantReportModal}>
      <ModalC
        height={600}
        title={'单租户报告申请'}
        visible={visible}
        maskClosable={false}
        onOk={() => {
          const formData = formRef.current.getFormGroupData();
          if (!formData) return;
          const payload = {
            productList: dataSource.length === 0 ? undefined : dataSource.map((v) => v.gzCode), // 产品列表
            reportDate: moment(formData.reportingDate).format('YYYY-MM-DD HH:mm:ss'), // 报告日期
            needPenetrate: formData.isPenetrates === '0', // 是否穿透
            managerName, // 租户名称
            scene: formData.scenarioName, // 情景名称
            stressTestTemplate: formData.modelName, // 模板名称
          };
          if (!payload.productList) return message.warning('请设置要出具报告的产品!');
          operate(true, payload);
        }}
        onCancel={() => operate(false)}
        width={900}
      >
        <div>
          <FormGroup
            autoLayout={false}
            rowNumber={3}
            dataSource={[
              {
                dataIndex: 'reportingDate',
                title: '报告日期',
                type: DATA_ENTRY.SINGLEDATE,
                initialValue: initDate,
                formItemLayout,
                allowClear: false,
                rules: [{ required: true, message: '请输入报告日期！' }],
                onChange: (e) => setInitDate(moment(e)),
              },
              {
                dataIndex: 'scenarioName',
                title: '情景名称',
                showSearch: true,
                filterOption: (input, option) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                },
                type: DATA_ENTRY.SELECT,
                formItemLayout,
                rules: [{ required: true, message: '请选择情景名称！' }],
                positionBody: true,
                dataSource: sceneList || [],
                allowClear: true,
              },
              {
                dataIndex: 'modelName',
                title: '模板名称',
                filterOption: (input, option) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 || option.props.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                },
                showSearch: true,
                type: DATA_ENTRY.SELECT,
                formItemLayout,
                rules: [{ required: true, message: '请选择模板名称！' }],
                positionBody: true,
                dataSource: templateList || [],
                allowClear: true,
              },
              {
                dataIndex: 'isPenetrates',
                title: '是否穿透',
                type: DATA_ENTRY.SELECT,
                formItemLayout,
                initialValue: '1',
                rules: [{ required: true, message: '请选择是否穿透！' }],
                dataSource: [
                  {
                    title: '是',
                    value: '0',
                  },
                  {
                    title: '否',
                    value: '1',
                  },
                ],
                allowClear: true,
              },
              {
                dataIndex: 'tenant',
                title: '租户',
                type: DATA_ENTRY.TENANT,
                rules: [{ required: true, message: '请选择租户！' }],
                formItemLayout,
                allowClear: false,
                onChange: (e) => {
                  changeTenant(e);
                },
              },
            ]}
            onRef={(ref) => {
              formRef.current = ref;
            }}
          />
          <SecondHeaderC title='产品列表' />
          {/* 查询栏 */}
          <div>
            <AdvancedSearch
              parentId={'SingleTenantReportModal'}
              dataSource={[
                {
                  dataIndex: ['startDateStart', 'startDateEnd'],
                  title: '起始日区间',
                  type: DATA_ENTRY.RANGEDATE,
                  initialValue: [null, initDate],
                  disableFuture: false,
                  allowClear: true,
                },
                {
                  dataIndex: ['endDateStart', 'endDateEnd'],
                  title: '到期日区间',
                  type: DATA_ENTRY.RANGEDATE,
                  initialValue: [moment(initDate).add(1, 'days'), null],
                  disableFuture: false,
                  allowClear: true,
                },
                {
                  dataIndex: 'productStatus',
                  title: '产品状态',
                  type: DATA_ENTRY.SELECT,
                  dataSource: dictMapSelect.BAXX_CPZT,
                  allowClear: true,
                  showSearch: false,
                  isMultiple: true,
                },
              ]}
              onQuery={handleSearch}
              onClear={handleSearch}
            />
          </div>
          {/* 操作栏 */}
          <div className={styles.operate}>
            <div>
              <div className={styles.ProductListC}>
                <Form>
                  <ProductListC
                    dataType={2}
                    currentTenant={currentTenant}
                    onGetProductListData={onGetProductListData}
                    positionBody={true}
                    form={props.form}
                    dataIndex='productdataIndex'
                    initialValue={undefined}
                    onRef={(ref) => (productListRef.current = ref)}
                    onChange={(e) => handleSelectProduct(e)}
                  />
                </Form>
              </div>
              <div className={styles.num}>
                {dataSource.length}/{productNum}
              </div>
            </div>
            <div>
              <Space>
                <PrimaryGhostC title={'批量删除'} disabled={selectedRowKeys.length === 0} onClick={batchDel} />
                <Popover
                  open={dataCompareOpen}
                  onOpenChange={(e) => setDataCompareOpen(e)}
                  content={
                    <>
                      <Space direction={'vertical'}>
                        <UploadC accept={'.xls,.xlsx'} type={2} showUploadList={false} onUpload={(e) => handleDataComparison(e)} />
                      </Space>
                    </>
                  }
                  title={
                    <span>
                      请导入excel文件
                      <br />
                      与当前产品列表进行产品比对
                    </span>
                  }
                  trigger='click'
                >
                  <PrimaryGhostC title={'数据对比'} disabled={dataSource.length === 0} />
                </Popover>
                <PrimaryGhostC title={'导出'} disabled={dataSource.length === 0} onClick={exportCurrentProduct} />
              </Space>
            </div>
          </div>
          <div id={'currentScrollTable'}>
            <TableC
              bigTable={true}
              columns={widthColumns}
              dataSource={dataSource}
              loading={loading}
              scroll={{ y: 500 }}
              hidePage={true}
              onChange={changeTable}
              rowKey='gzCode'
              rowClassName={(record) => (record.gzCode === defaultSelect ? 'defaultSelect' : '')}
              rowSelection={{
                selectedRowKeys,
                onChange: (rowKeys, selectedRows) => setSelectedRowKeys(rowKeys),
              }}
            />
          </div>
        </div>
      </ModalC>
    </div>
  );
};
SingleTenantReportModal.propTypes = {
  visible: PropTypes.bool.isRequired, // 显示
  operate: PropTypes.func.isRequired, // 操作函数
};
const FormRefSingleTenantReportModal = Form.create()(SingleTenantReportModal);
const mapState = ({ productManageM, loading, globalM, tenantManageM }) => ({ productManageM, loading: loading.effects['productManageM/getList'], globalM, tenantManageM });
export default connect(mapState)(FormRefSingleTenantReportModal);
